<?php
namespace FastPHP\Library;

class Request
{
    protected static $instance = null;
    protected $method;
    protected $params = [];
    protected $headers = [];
    protected $cache = [];

    private function __construct() {
        $this->method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
        $this->params = array_merge($_GET, $_POST, $_FILES);
        $this->headers = $this->parseHeaders();
    }

    public static function instance()
    {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    // 获取请求方法
    public function method()
    {
        return $this->method;
    }

    // 判断请求类型
    public function is($type)
    {
        return $this->method === strtoupper($type);
    }

    // 获取参数
    public function param($name = null, $default = null)
    {
        if ($name === null) return $this->params;
        return isset($this->params[$name]) ? $this->params[$name] : $default;
    }

    // 获取GET参数
    public function get($name = null, $default = null)
    {
        if ($name === null) return $_GET;
        return isset($_GET[$name]) ? $_GET[$name] : $default;
    }

    // 获取POST参数
    public function post($name = null, $default = null)
    {
        if ($name === null) return $_POST;
        return isset($_POST[$name]) ? $_POST[$name] : $default;
    }

    // 获取文件上传
    public function file($name = null)
    {
        if ($name === null) return $_FILES;
        return isset($_FILES[$name]) ? $_FILES[$name] : null;
    }

    // 获取服务器变量
    public function server($name = null, $default = null)
    {
        if ($name === null) return $_SERVER;
        return isset($_SERVER[$name]) ? $_SERVER[$name] : $default;
    }

    // 获取HTTP头信息
    public function header($name = null, $default = null)
    {
        if (empty($this->headers)) $this->headers = $this->parseHeaders();
        if ($name === null) return $this->headers;
        $key = strtolower($name);
        return isset($this->headers[$key]) ? $this->headers[$key] : $default;
    }

    // 判断是否AJAX请求
    public function isAjax()
    {
        $header = strtolower($this->header('x-requested-with', ''));
        return $header === 'xmlhttprequest';
    }

    // 判断是否POST请求
    public function isPost()
    {
        return $this->method === 'POST';
    }
    // 判断是否GET请求
    public function isGet()
    {
        return $this->method === 'GET';
    }
    // 判断是否PUT请求
    public function isPut()
    {
        return $this->method === 'PUT';
    }
    // 判断是否DELETE请求
    public function isDelete()
    {
        return $this->method === 'DELETE';
    }

    // 解析HTTP头
    protected function parseHeaders()
    {
        $headers = [];
        foreach ($_SERVER as $k => $v) {
            if (strpos($k, 'HTTP_') === 0) {
                $key = strtolower(str_replace('_', '-', substr($k, 5)));
                $headers[$key] = $v;
            }
        }
        return $headers;
    }

    // 获取当前URL
    public function url()
    {
        $scheme = $this->isSsl() ? 'https://' : 'http://';
        $host = $_SERVER['HTTP_HOST'] ?? '';
        $uri = $_SERVER['REQUEST_URI'] ?? '';
        return $scheme . $host . $uri;
    }

    // 获取域名
    public function domain()
    {
        $scheme = $this->isSsl() ? 'https://' : 'http://';
        $host = $_SERVER['HTTP_HOST'] ?? '';
        return $scheme . $host;
    }

    // 获取客户端IP
    public function ip()
    {
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
        } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = '0.0.0.0';
        }
        return $ip;
    }

    // 获取端口
    public function port()
    {
        return $_SERVER['SERVER_PORT'] ?? 80;
    }

    // 获取URL后缀
    public function ext()
    {
        $uri = $_SERVER['REQUEST_URI'] ?? '';
        if (preg_match('/\.([a-zA-Z0-9]+)$/', $uri, $m)) {
            return strtolower($m[1]);
        }
        return '';
    }

    // 是否SSL
    public function isSsl()
    {
        if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === '1' || strtolower($_SERVER['HTTPS']) === 'on')) {
            return true;
        }
        if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) {
            return true;
        }
        return false;
    }

    // 伪静态（PATH_INFO）
    public function pathinfo()
    {
        return $_SERVER['PATH_INFO'] ?? '';
    }

    // 参数绑定（自动获取参数，优先POST、GET）
    public function input($name, $default = null)
    {
        if (isset($_POST[$name])) return $_POST[$name];
        if (isset($_GET[$name])) return $_GET[$name];
        return $default;
    }

    // 请求缓存接口（预留）
    public function cache($key, $value = null)
    {
        if ($value === null) {
            return $this->cache[$key] ?? null;
        } else {
            $this->cache[$key] = $value;
        }
    }

    // 获取当前控制器名称
    public function controller()
    {
        if (isset($GLOBALS['_ROUTER_CONTROLLER'])) {
            return $GLOBALS['_ROUTER_CONTROLLER'];
        }
        
        // 从URL中解析
        $pathInfo = $this->pathinfo();
        $pathParts = explode('/', trim($pathInfo, '/'));
        
        if (isset($pathParts[1])) {
            return ucfirst($pathParts[1]);
        }
        
        return 'Index';
    }

    // 获取当前操作名称
    public function action()
    {
        if (isset($GLOBALS['_ROUTER_ACTION'])) {
            return $GLOBALS['_ROUTER_ACTION'];
        }
        
        // 从URL中解析
        $pathInfo = $this->pathinfo();
        $pathParts = explode('/', trim($pathInfo, '/'));
        
        if (isset($pathParts[2])) {
            return $pathParts[2];
        }
        
        return 'index';
    }

    // 获取当前分组名称
    public function group()
    {
        if (isset($GLOBALS['_ROUTER_GROUP'])) {
            return $GLOBALS['_ROUTER_GROUP'];
        }
        
        // 从URL中解析
        $pathInfo = $this->pathinfo();
        $pathParts = explode('/', trim($pathInfo, '/'));
        
        if (isset($pathParts[0])) {
            return $pathParts[0];
        }
        
        return 'home';
    }

    // 获取当前模块名称（别名）
    public function module()
    {
        return $this->group();
    }

    // 获取当前路由参数
    public function route($name = null, $default = null)
    {
        if (isset($GLOBALS['_ROUTER_PARAMS'])) {
            $params = $GLOBALS['_ROUTER_PARAMS'];
        } else {
            $params = [];
        }
        
        if ($name === null) {
            return $params;
        }
        
        return isset($params[$name]) ? $params[$name] : $default;
    }
} 